#!/bin/sh
#
# Copyright (C) 2000-2022 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Run a simple backup of the Bacula build directory and see if bacula is
# respecting the maximum concurrent job (MJC) and the enabled flag
#
TestName="mjc-test"
JobName=backup
. scripts/functions

scripts/cleanup
scripts/copy-confs

#
# Zap out any schedule in default conf file so that
#  it doesn't start during our test
#
outf="$tmp/sed_tmp"
echo "s%  Schedule =%# Schedule =%g" >${outf}
cp $scripts/bacula-dir.conf $tmp/1
sed -f ${outf} $tmp/1 >$scripts/bacula-dir.conf

change_jobname BackupClient1 $JobName
start_test

cat <<END_OF_DATA >$tmp/bconcmds
@$out /dev/null
messages
@$out $tmp/log1.out
label volume=TestVolume001 storage=File1 pool=File slot=1 drive=0
show client
setbandwidth limit="100 kb/s" client
run job=$JobName level=full yes
@sleep 5
status dir
@sleep 5
run job=$JobName level=full comment="Should be waiting for Maximum Concurrent Job" yes
@sleep 5
status dir
@# The following reload command is causing a bug with the current code
reload
@sleep 2
run job=$JobName level=full comment="Should be waiting for Maximum Concurrent Job" yes
@sleep 5
@$out $tmp/log3.out
@# ##################################################################################
@# If everything is alright, we should find two jobs waiting for MaximumConcurrentJob
@# ##################################################################################
status dir
@# ##################################################################################
@$out $tmp/log1.out
setbandwidth limit="10000000 kb/s" client
wait
messages
@# 
@# now do a restore
@#
@$out $tmp/log2.out  
restore where=$tmp/bacula-restores select all done
yes
wait
messages
@$out $tmp/log4.out
@# ################################################################
@# Test the enable flag now
@# ################################################################
disable client
disable job=$JobName
show client
show job=$JobName
@# do the reload now and check the Enabled=0 again
reload
show client
show job=$JobName
disable job
.
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File1
stop_bacula

check_two_logs
check_restore_diff

nb=$(grep "is waiting" $tmp/log3.out | wc -l)
if [ $nb -ne 2 ]; then
    print_debug "ERROR: Should find two jobs in $tmp/log3.out waiting for Maximum Concurrent Jobs, got $nb"
    estat=1
fi

nb=$(awk "/^(Job|Client): .+ Enabled=0/ { print $1 }" $tmp/log4.out | wc -l)
if [ $nb -ne 4 ]; then
    print_debug "ERROR: Should find both Client and Job with Enabled=0 before and after the reload in $tmp/log4.out"
    estat=1
fi

end_test
